<template>
  <basic-container>
    <!-- <el-page-header @back="goBack" content="创建任务"></el-page-header> -->
    <div>
      <el-button @click="goBack" icon="el-icon-back" type="text" size="small">返回</el-button>
    </div>
    <el-divider></el-divider>
    <el-row class="mar-t-40" :gutter="20">
      <el-col :span="12">
        <el-form ref="model" :rules="rules" :model="model" size="medium" label-width="120px">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="model.name"></el-input>
          </el-form-item>
          <el-form-item label="Measure" prop="measureId">
            <el-select :loading = "measuresLoading" loading-text="加载中..." class="dis-b" v-model="model.measureId" @change="measuresChange" placeholder="请选择">
              <el-option
                v-for="item in measures"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Cron表达式" prop="expression">
            <el-popover
            placement="bottom-start"
            trigger="click">
              <template slot="reference">
                <el-input readonly :value="model.expression">
                </el-input>
              </template>
              <div class="crontab-box">
                <v-crontab v-model="model.expression"></v-crontab>
              </div>
            </el-popover>
            <!-- <el-input v-model="model.expression"></el-input> -->
            <!-- <v-crontab v-model="model.expression"></v-crontab> -->
          </el-form-item>
          <template v-if="model.measureId && sliders.length">
            <el-divider content-position="left">设置数据范围</el-divider>
            <div v-for="(item , index) in sliders" :key="index + ''">
              <p class="pad-l-30 lh-40">设置 {{item.name}} 数据范围(size = {{item.size}})</p>
              <el-form-item label="开始值">
                <el-input-number v-model="item.value[0]" :max="0"></el-input-number>
              </el-form-item>
              <el-form-item label="结束值">
                <el-input-number v-model="item.value[1]" :max="0"></el-input-number>
              </el-form-item>
            </div>
          </template>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('model')">立即创建</el-button>
            <el-button @click="goBack">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </basic-container>
</template>
<script>
import { griffinService } from '@/api/griffin'
import { vCrontab } from '@/view-module/dolphin-scheduler/common/components/crontab'
export default {
  components: {
    vCrontab
  },
  data(){
    return {
      model: {
        expression: '0 0 * * * ? *',
        name: '',
        measureId: null
      },
      measures: [],
      measuresLoading: false,
      selectMeasure: null,
      rules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        measureId: [
          { required: true, message: '请输入选择Measure', trigger: 'blur' }
        ],
        expression: [
          { required: true, message: '请输入Cron表达式', trigger: 'blur' }
        ]
      },
      sliders: [],
      sliderMinValue: []
    }
  },
  mounted(){
    this.measuresLoading = true;
    griffinService.getMeasures({
      type: 'griffin'
    }).then(
      res => {
        this.measuresLoading = false;
        this.measures = res.data || [];
      }
    )
  },
  methods: {
    goBack(){
      this.$parent.show = 'list';
    },
    onSubmit(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitData();
        } else {
          return false;
        }
      });
    },
    measuresChange(){
      this.selectMeasure = this.measures.find(item => item.id == this.model.measureId);
      console.log(this.selectMeasure);
      this.sliders = [];
      this.sliderMinValue = [];
      if(this.selectMeasure['data.sources']){
        this.selectMeasure['data.sources'].forEach(
          source => {
            if(source.connectors){
              source.connectors.forEach(
                item => {
                  let dataSegment = {
                    value: [-1 , 0],
                    name: `${item['config']['database']}.${item['config']['table.name']}`,
                    size: item['data.unit'],
                    dataConnectorName: item.name
                  }
                  this.sliderMinValue.push(-10);
                  this.sliders.push(dataSegment);
                }
              )
            }
          }
        )
      }
    },
    sliderValueChange(index){
      let value = this.sliders[index].value[0];
      this.sliderMinValue[index] = Math.ceil(value / 10) * 10 - 10;
    },
    submitData(){
      if(!this.$store.state.dag.projectId || !this.$store.state.dag.projectName){
        this.$message({
          type: 'error',
          message: '数据错误，请返回项目重新进入。'
        });
        return false;
      }
      let body = {
        'job.name': this.model.name,
        'cron.expression': this.model.expression,
        'measure.id': this.model.measureId,
        'job.type': 'batch',
        'cron.time.zone': griffinService.getBrowserTimeZone(),
        'data.segments': [],
        'projectId': this.$store.state.dag.projectId,
        'projectName': this.$store.state.dag.projectName
      }
      this.sliders.forEach(
        item => {
          let beginStr = this.getTimeByUnit(item.value[0], item.size);
          let lengthStr = this.getTimeByUnit(item.value[1] - item.value[0], item.size);
          body['data.segments'].push({
            'as.baseline': true,
            'data.connector.name': item['dataConnectorName'],
            'segment.range': {
              begin: beginStr,
              length: lengthStr
            }
          })
        }
      )
      griffinService.saveJob(body).then(
        res => {
          if(res['data']['id']){
            this.$message({
              type: 'success',
              message: '操作成功'
            })
            this.goBack();
          }
        }
      )
    },
    getTimeByUnit(multiplier, unit) {
      let regex = /^(\d+)([a-zA-Z]+)$/g;
      let arr = regex.exec(unit);
      if (arr.length > 2) {
        let n = parseInt(arr[1]);
        return ((n * multiplier).toString() + arr[2]);
      } else {
        return multiplier.toString();
      }
    }
  }
}
</script>